import json
from pathlib import Path
from typing import Any, Dict

_SETTINGS_CACHE: Dict[str, Any] | None = None


def get_project_root() -> Path:
    # Project root assumed to be the directory containing this file two levels up
    return Path(__file__).resolve().parents[2]


def get_settings() -> Dict[str, Any]:
    global _SETTINGS_CACHE
    if _SETTINGS_CACHE is not None:
        return _SETTINGS_CACHE

    root = get_project_root()
    settings_path = root / "config" / "settings.json"
    if not settings_path.exists():
        raise FileNotFoundError(f"Settings file not found: {settings_path}")

    with settings_path.open("r", encoding="utf-8") as f:
        _SETTINGS_CACHE = json.load(f)
    return _SETTINGS_CACHE


def ensure_data_dirs() -> Dict[str, Path]:
    """Ensure data/log directories exist, return their paths."""
    settings = get_settings()
    root = get_project_root()

    data_dir = root / settings["system"]["data_directory"].strip("./\\")
    log_dir = root / settings["system"]["log_directory"].strip("./\\")

    for p in [data_dir, log_dir, data_dir / "stocks" / "daily", data_dir / "stocks" / "hourly", data_dir / "stocks" / "minute", data_dir / "backups", data_dir / "metadata"]:
        p.mkdir(parents=True, exist_ok=True)

    return {"data_dir": data_dir, "log_dir": log_dir}